/*
 * @Author: kanglang
 * @Date: 2021-02-23 11:22:57
 * @LastEditors: zeki mini
 * @LastEditTime: 2021-06-10 15:46:57
 * @Description:  对公账户信息审核状态
 */

import React from 'react';
import {
  View,
  StyleSheet,
  Image,
  Text,
  ScrollView,
  NativeModules,
  SafeAreaView,
  PixelRatio
} from 'react-native';
import { Button, msg, FormInput, cache } from '@/common';
import {
  px2dp, priceColor, mainBgColorWhite, fontColorBlack,
  fontColorDeepGray, mainBgColorLightGray,
} from '@/styles';
import AsyncStorage from '@react-native-community/async-storage';
import { iconFailureTextRed } from '@/images';
import { uploadImage } from '@/config';
import businessApi from '@/api/business';
import Picker from '@/common/picker';
import BusinessFormSelect from '../components/business-form-select';
import ExampleImager from './components/example-imager';

const { Submit } = Button;

export default class CorporateAccountInfoCerti extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      custName: '',
      cardNo: '',
      file: '',
      auditState: 0,
      reason: '',
      name: '广发银行',
      curBankId: '',
      childBankList: [],
      curOpenBankName: '',
      id: '',
      modalVisible: false
    };
  }

  componentDidMount() {
    AsyncStorage.getItem(cache.CURRENT_LEGAL).then((val) => {
      let currentLegal = JSON.parse(val);
      this.setState({ ...currentLegal }, () => {
        const { custId } = this.state;
        businessApi.getLegalBankCard({ custId }).then(res => {
          if (res.success && res.data) {
            this.setState({
              auditState: res.data.auditState,
              custName: res.data.custName,
              cardNo: res.data.cardNo,
              file: res.data.file,
              name: res.data.name,
              curOpenBankName: res.data.openingBank,
              reason: res.data.reason,
              id: res.data.id
            });
          }
        });
      });
    });
    businessApi.findOpenBankIdLikeName().then(res => {
      if (res.success) {
        const childBankList = res.data || [];
        this.setState({
          childBankList,
        });
      }
    });
    // 监听银行选择
    msg.on('bankDataSelect', (bankDataSelect) => {
      if (bankDataSelect.type == 'openBank') {
        this.setState({ name: bankDataSelect.name });
      }
      if (bankDataSelect.type == 'openBankBranch') {
        this.setState({ curOpenBankName: bankDataSelect.bankNameInfo });
      }
    });
  }

  componentWillUnmount() {
    msg.off('bankDataSelect');
  }

  render() {
    const { custName, cardNo, file, name, curOpenBankName, auditState, reason, modalVisible } = this.state;
    // const curBankName = (curOpenBankName && curOpenBankName.substr(10)) || curOpenBankName;
    const curBankName = curOpenBankName + curOpenBankName;
    return (
      <SafeAreaView style={styles.container}>
        <ScrollView style={styles.inner}>
          {
            auditState == 2 &&
            <View style={styles.reasonBox}>
              <Text style={styles.stepTip}> * 失败原因：</Text>
              <View style={{ flex: 1 }}>
                <Text style={styles.stepReason}>{reason}</Text>
              </View>
            </View>
          }
          <View style={styles.firstPart}>
            {auditState == 2 && <Image style={styles.dabiao} source={iconFailureTextRed} />}
            <FormInput
              label={this.formItem('开户名称')}
              labelWidth={{ width: px2dp(200) }}
              placeholder='请输入开户名'
              defaultValue={custName}
              inputType={1}
              textStyles={{ textAlign: 'left' }}
              boxStyle={{ height: 60, paddingLeft: 0 }}
              onChange={(value) => {
                this.onChange('custName', value);
              }}
              disabled={auditState != 2}
            />

            <BusinessFormSelect
              label='开户银行'
              defaultValue='请选择开户银行'
              value={name}
              onPress={this.selectOpenBank}
              disabled={auditState != 2}
            />
            <BusinessFormSelect
              label='开户支行'
              defaultValue='请选择开户支行'
              value={curBankName}
              onPress={this.selectOpenAccountChildBank}
              disabled={auditState != 2}
            />
            <FormInput
              label={this.formItem('银行账号')}
              labelWidth={{ width: px2dp(200) }}
              placeholder='请输入银行卡号'
              defaultValue={cardNo}
              inputType={1}
              textStyles={{ textAlign: 'left' }}
              boxStyle={{ height: 60, borderBottomColor: 'transparent', paddingLeft: 0 }}
              onChange={(value) => {
                this.onChange('cardNo', value);
              }}
              disabled={auditState != 2}
            />
          </View>
          {/* <View style={styles.licenseBox} >
                        <View style={styles.labelBox}>
                            {this.formItem('业务授权书')}
                            {auditState == 2 &&
                                <Text
                                    style={styles.tempText}
                                    onPress={this.checkTemp}
                                >
                                    查看示例
                            </Text>
                            }
                        </View>
                        <View style={styles.licenseBtnBox} >
                            <TouchableOpacity
                                onPress={this.selectImage}
                            >
                                {
                                    !!file ?
                                        <Image
                                            style={styles.licenseImgStyle}
                                            source={{ uri: file }}
                                        /> :
                                        <View style={styles.defaultAddBox}>
                                            <Image
                                                style={styles.addImgIcon}
                                                source={iconAdd}
                                            />
                                        </View>
                                }
                            </TouchableOpacity>
                        </View>

                    </View> */}
          {
            auditState == 2 &&
            <View style={styles.bottomBtnBox}>
              <View style={styles.submitBox}>
                <Submit
                  text='取消'
                  btnTextStyle={styles.preStepText}
                  boxStyle={styles.preBoxStyle}
                  onClick={this.goBack}
                />
              </View>
              <View style={styles.submitBox}>
                <Submit
                  text='重新提交'
                  btnTextStyle={styles.nextStepText}
                  boxStyle={styles.nextBoxStyle}
                  onClick={this.reSubmit}
                />
              </View>
            </View>
          }
          <ExampleImager
            type={3}
            modalVisible={modalVisible}
            onChange={this.checkTemp}
          />
        </ScrollView>
      </SafeAreaView>
    );
  }

  formItem = (name) => {
    return (
      <>
        <Text style={{ color: priceColor }}>＊</Text>
        <Text style={{ color: fontColorDeepGray, fontSize: px2dp(28) }}>{name}</Text>
      </>
    );
  }

  checkTemp = () => {
    const { modalVisible } = this.state;
    this.setState({
      modalVisible: !modalVisible,
    });
  }

  goBack = () => {
    msg.emit('router: back');
  }

  reSubmit = () => {
    const { custName, cardNo, file, name, curOpenBankName, custId, id } = this.state;
    if (!custName) return msg.emit('app:tip', { text: '请填写开户名称' });
    if (!name) return msg.emit('app:tip', { text: '请选择开户行' });
    if (!curOpenBankName) return msg.emit('app:tip', { text: '请选择开户行支行' });
    // if (!file) return msg.emit('app:tip', { text: '请上传业务授权书' });
    if (!cardNo) return msg.emit('app:tip', { text: '请填写银行卡号' });
    const corporateAccountInfoCertiParams = {
      id,
      custName,
      cardNo,
      file,
      name,
      openingBank: curOpenBankName,
      custId
    };
    businessApi.updateLegalBankCard(corporateAccountInfoCertiParams).then(res => {
      if (res.success) {
        msg.emit('app:tip', { text: '提交成功' });
        msg.emit('router: refreshRoute', {
          routeName: 'BusinessData',
        });
        msg.emit('router: goToNext', {
          routeName: 'BusinessData',
          custId
        });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  }

  // 输入框变化监听
  onChange = (type, value) => {
    this.setState({ [type]: value });
  }

  // 选择图片
  selectImage = () => {
    const { auditState } = this.state;
    if (auditState != 2) return;
    NativeModules.DataModule.chooseImage((path, imageBase64) => {
      this.IdCardUpload(path);
    });
  }

  // 上传图片
  IdCardUpload(path) {
    msg.emit('app:selfTip', {
      isVisible: true,
      text: '图片上传中...',
      icon: 'loading',
      style: { zIndex: 1 }
    });
    uploadImage('upload?dirName=businessCert', path).then(res => {
      console.log(`uploadImage：${JSON.stringify(res)}`);
      if (res.success) {
        this.setState({ file: res.data.url });
      } else {
        msg.emit('app:messageBox', {
          isVisible: true,
          title: '温馨提示',
          text: '上传失败，请重试',

          isClickBg: false,
          okFn: () => { },
        });
      }
      msg.emit('app:selfTip', {
        isVisible: false,
      });
    }).catch(err => {
      console.log(err);
      msg.emit('app:selfTip', {
        isVisible: false,
      });
      // 请求失败
      msg.emit('app:messageBox', {
        isVisible: true,
        title: '温馨提示',
        text: '上传失败，请重试',

        isClickBg: false,
        okFn: () => { },
      });
    });
  }

  // 选择开户行
  selectOpenBank = () => {
    msg.emit('router: goToNext', {
      routeName: 'B2BCorporateAccountBankSelect',
      type: 'openBank'
    });
  }

  // 选择开户支行
  selectOpenAccountChildBank = () => {
    const { name } = this.state;
    msg.emit('router: goToNext', {
      routeName: 'B2BCorporateAccountBankSelect',
      type: 'openBankBranch',
      bankName: name
    });
    // const { childBankList } = this.state;
    // let pickerL = [];
    // childBankList.map((item) => {
    //     pickerL.push(item.bankNameInfo);
    // });
    // this.showPicker('切换支行', pickerL);
  }

  showPicker = (title, dataList) => {
    const { childBankList, curBankId } = this.state;
    let currentName = '';
    childBankList.map((item, index) => {
      if (item.id == curBankId) {
        currentName = item.bankNameInfo;
      }
    });
    Picker.init({
      pickerTitleText: title,
      pickerCancelBtnText: '取消',
      pickerConfirmBtnColor: [186, 145, 74, 1],
      pickerCancelBtnColor: [102, 101, 100, 1],
      pickerConfirmBtnText: '确定',
      selectedValue: [currentName],
      pickerBg: [255, 255, 255, 1],
      pickerToolBarBg: [255, 255, 255, 1],
      pickerFontColor: [186, 145, 74, 1],
      pickerRowHeight: 40,
      pickerData: dataList,
      onPickerConfirm: (pickedValue, pickedIndex) => {
        childBankList.forEach(item => {
          if (item.bankNameInfo == pickedValue.toString()) {
            this.setState({
              curBankId: item.id,
              curOpenBankName: item.bankNameInfo,
            });
          }
        });
      },
      onPickerCancel: (pickedValue, pickedIndex) => {
      },
      onPickerSelect: (pickedValue, pickedIndex) => {

      },
    });
    Picker.show();
  };
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorWhite,
  },
  inner: {
    flex: 1,
    backgroundColor: mainBgColorLightGray
  },
  reasonBox: {
    backgroundColor: '#FFF5F5',
    paddingLeft: px2dp(32),
    paddingVertical: px2dp(24),
    flexDirection: 'row'
  },
  stepTip: {
    color: '#EB2F2F',
    fontSize: px2dp(28),
  },
  stepReason: {
    color: '#EB2F2F',
    fontSize: px2dp(28),
    justifyContent: 'flex-start',
    alignItems: 'flex-start',
    flexWrap: 'wrap'
  },
  firstPart: {
    backgroundColor: mainBgColorWhite,
    paddingHorizontal: px2dp(32),
    // paddingBottom: px2dp(60)
  },
  fontTitle: {
    color: fontColorBlack,
    fontSize: px2dp(32),
    marginTop: px2dp(32),
    lineHeight: px2dp(40)
  },
  fontText: {
    color: fontColorBlack,
    fontSize: px2dp(28),
    lineHeight: px2dp(38)
  },
  tempText: {
    color: '#2293FF',
    fontSize: px2dp(28),
    textDecorationLine: 'underline'
  },
  btnBox: {
    flex: 1,
    alignItems: 'center',
    marginTop: px2dp(130)
  },
  boxStyle: {
    width: px2dp(640),
    height: px2dp(96),
    borderRadius: px2dp(12),
    overflow: 'hidden',
  },
  longTimeBox: {
    flexDirection: 'row',
    marginRight: px2dp(40)
  },
  longTime: {
    color: '#b2b2b2',
    marginLeft: px2dp(16)
  },
  itemBox: {
    flexDirection: 'row',
    alignItems: 'center',
    borderBottomWidth: 1 / PixelRatio.get(),
    borderBottomColor: '#ebebeb',
    width: '100%',
    height: 60,
  },
  labelBox: {
    flexDirection: 'row',
    alignItems: 'center',
    width: px2dp(190)
  },
  addressBox: {
    flexDirection: 'row',
    alignItems: 'center',
    marginLeft: px2dp(10)
  },
  addressImgBox: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  iconMore: {
    width: px2dp(24),
    height: px2dp(24),
    marginLeft: px2dp(16)
  },
  timeImg: {
    width: px2dp(36),
    height: px2dp(36),
    marginRight: px2dp(16)
  },
  licenseBox: {
    justifyContent: 'space-between',
    backgroundColor: mainBgColorWhite,
    paddingHorizontal: px2dp(32),
    paddingVertical: px2dp(40),
    marginTop: px2dp(24),
  },
  licenseBtnBox: {
    flexDirection: 'row',
    alignItems: 'center',
    width: px2dp(190),
    marginTop: px2dp(40),
    paddingLeft: px2dp(32)
  },
  licenseImgStyle: {
    width: px2dp(160),
    height: px2dp(160),
  },
  defaultAddBox: {
    width: px2dp(160),
    height: px2dp(160),
    backgroundColor: mainBgColorLightGray,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: px2dp(8),
  },
  addImgIcon: {
    width: px2dp(48),
    height: px2dp(48)
  },
  bottomBtnBox: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: px2dp(40),
    height: px2dp(200)
  },
  submitBox: {
    flex: 1,
    alignItems: 'center'
  },
  preStepText: {
    fontSize: px2dp(32),
    color: '#686764'
  },
  nextStepText: {
    fontSize: px2dp(32),
  },
  preBoxStyle: {
    width: px2dp(280),
    borderRadius: px2dp(12),
    backgroundColor: '#E6E6E5'
  },
  nextBoxStyle: {
    width: px2dp(280),
    borderRadius: px2dp(12),
  },
  addressText: {
    color: '#b2b2b2',
    maxWidth: '80%'
  },
  dabiao: {
    position: 'absolute',
    width: px2dp(151),
    height: px2dp(114),
    right: px2dp(32),
    top: px2dp(25),
    zIndex: 1
  }
});
